---
title: Focus Trap
description: Using the Focus Trap utility in your project.
package: "@zag-js/focus-trap"
---

The focus trap utility is used to trap focus within a DOM element, preventing
users from tabbing outside of a specific region.

<Resources pkg="@zag-js/focus-trap" />

**Features**

- Handles edge cases like hidden elements
- Works with shadow DOM
- Supports nested focus traps
- Follows ARIA-controlled elements

## Installation

```bash
npm install @zag-js/focus-trap
```

## Usage

```js
import { trapFocus } from "@zag-js/focus-trap"

// Trap focus within an element
const restore = trapFocus(element, {
  initialFocus: "#first-input",
  returnFocusOnDeactivate: true,
})

// Later, release the trap
restore()
```

### Framework Usage

<CodeSnippet id="focus-trap/usage.mdx" />

## API Reference

### trapFocus

```ts
function trapFocus(
  element: HTMLElement | null | (() => HTMLElement | null),
  options?: TrapFocusOptions,
): () => void
```

Creates a focus trap for the specified element.

**Parameters:**

- `element` - The container element to trap focus within, or a function that
  returns the element
- `options` - Configuration options for the focus trap

**Returns:** A cleanup function that deactivates the focus trap when called.

### Options

| Property                   | Description                                      |
| -------------------------- | ------------------------------------------------ |
| `initialFocus`             | Element to receive focus on activation           |
| `fallbackFocus`            | Fallback element if no tabbable elements found   |
| `returnFocusOnDeactivate`  | Return focus to previous element on deactivation |
| `escapeDeactivates`        | Allow ESC key to deactivate trap                 |
| `clickOutsideDeactivates`  | Deactivate trap on outside click                 |
| `allowOutsideClick`        | Allow outside clicks without deactivating        |
| `preventScroll`            | Prevent scrolling when focusing                  |
| `delayInitialFocus`        | Delay initial focus to prevent event capture     |
| `followControlledElements` | Include ARIA-controlled elements                 |
| `getShadowRoot`            | Enable shadow DOM traversal                      |
| `isKeyForward`             | Custom forward navigation key                    |
| `isKeyBackward`            | Custom backward navigation key                   |
| `onActivate`               | Called before activation                         |
| `onPostActivate`           | Called after activation                          |
| `onDeactivate`             | Called before deactivation                       |
| `onPostDeactivate`         | Called after deactivation                        |
